import ScrollBarLayout from '@/components/ScrollBarLayout';
import Cls from 'classnames';
import { useCallback, useContext, useEffect, useState } from 'react';
import { ChangeControllerContext } from '../common/useOAContext';
import { Checkbox, Form, Spin, Tooltip, TreeSelect, message, Button } from 'antd';
import { useDescriptions, Descriptions } from '@/components/Descriptions';
import { downloadTemplate, getFileNameNotType, getLevelZeroJson, getLoadMapList, getSelectDataMapList, getTenantID, splitFileUrl } from '@/utils';
import { ILoadMapTypeAll } from '@/common';
import MyIcon from '@/components/MyIcon';
import { DetailServices } from '../services';
import { connect } from 'umi';
import moment from 'moment';
import { TypographyTitle } from '@/components/Typography/TypographyTitle';
import { getBaseUrl } from '@/services/urlconst';
import { readReadShowFileService } from '@/services/BaseLayout';
import { EyeOutlined } from '@ant-design/icons';

const DetailInfoCenterViewMainOA = ({ curRes }) => {
  /** 引入上下文 */
  const { styleFixCls, infoObj, taskId }: any = useContext(ChangeControllerContext);

  /**  获取数据字典 */
  const { loadMapInfo, mapLoading } = getLoadMapList([
    `${getTenantID()}${ILoadMapTypeAll.ASSET_TYPE}`, //资产类型
    `${getTenantID()}${ILoadMapTypeAll.AVERAGE_LIFE_METHOD}`, //折旧方式
    `${getTenantID()}${ILoadMapTypeAll.ASSET_SOURCE_TYPE}`, //资产来源
    `${getTenantID()}${ILoadMapTypeAll.MATERIAL_BRAND}`, //资产品牌
    `${getTenantID()}${ILoadMapTypeAll.ASSET_AREA}`, //资产存放地点
    `${getTenantID()}${ILoadMapTypeAll.MATERIAL_MIDI}`, //量化单位
  ]);

  /** 资产类型 */
  const assetType = getSelectDataMapList(loadMapInfo?.[`${getTenantID()}${ILoadMapTypeAll.ASSET_TYPE}`], 'name', 'id', true);

  const [changeFromRef] = Form.useForm(); // 表单实例

  const detailCallback = (res) => {
    if (res.msgFlag) {
      if (changeFromRef) {
        console.log(res?.obj);

        BasicMethods?.setFieldsValue({
          ...res?.obj,
          rangeDeptID: res?.obj?.rangeDeptID?.split(','),
          rangeAssetClassID: res?.obj?.rangeAssetClassID?.split(','),
          startTime: moment(res?.obj?.startTime).format('YYYY-MM-DD'),
          endTime: moment(res?.obj?.endTime).format('YYYY-MM-DD'),
          rangeStartDate: moment(res?.obj?.rangeStartDate).format('YYYY-MM-DD'),
          rangeEndDate: moment(res?.obj?.rangeEndDate).format('YYYY-MM-DD'),
          createTime: moment(res?.obj?.createTime).format('YYYY-MM-DD'),
        });
        ReMethods?.setFieldsValue({
          ...res?.obj,
          rangeDeptID: res?.obj?.rangeDeptID?.split(','),
          rangeAssetClassID: res?.obj?.rangeAssetClassID?.split(','),
          startTime: moment(res?.obj?.startTime).format('YYYY-MM-DD'),
          endTime: moment(res?.obj?.endTime).format('YYYY-MM-DD'),
          rangeStartDate: moment(res?.obj?.rangeStartDate).format('YYYY-MM-DD'),
          rangeEndDate: moment(res?.obj?.rangeEndDate).format('YYYY-MM-DD'),
          createTime: moment(res?.obj?.createTime).format('YYYY-MM-DD'),
        });
      }
    }
  };

  const { DetailPushRun, Detaildata, DetailPushLoading } = DetailServices(curRes, detailCallback);

  /** 轻阅读预览 */
  const { readReadShowFileRun } = readReadShowFileService();

  /**轻阅读预览 */
  const onOpenReadOfdWord = (fieldUrl: string) => {
    readReadShowFileRun({ fieldPath: `${getBaseUrl()}${fieldUrl}` });
  };

  useEffect(() => {
    const obj: any = {
      id: taskId?.id,
    };

    DetailPushRun(obj);
  }, [infoObj]);

  function addDisabledToTreeData(originalTreeData) {
    const newTreeData = originalTreeData?.map((node) => {
      const newNode = { ...node, disabled: true }; // 复制节点并添加disabled属性

      if (node.children) {
        newNode.children = addDisabledToTreeData(node.children); // 递归处理子节点
      }

      return newNode;
    });

    return newTreeData;
  }

  const schemasArr = useCallback(() => {
    let tempArr: any = [
      {
        field: `inventoryTitle`,
        label: `事项名称`,
        component: 'Input',
        disabled: true,
        placeholder: '自动带出',
        colSpan: 0,
      },
      {
        field: `startTime`,
        label: `盘点开始时间`,
        component: 'Input',
        disabled: true,
        placeholder: '自动带出',
      },
      {
        field: `endTime`,
        label: `盘点结束时间`,
        component: 'Input',
        disabled: true,
        placeholder: '自动带出',
      },
      {
        field: `rangeDeptID`,
        label: `部门范围`,
        component: 'Render',
        colSpan: 2,
        disabled: true,
        placeholder: '请输入',
        render: (text) => {
          return (
            <TreeSelect
              multiple
              style={{
                width: '100%',
              }}
              dropdownStyle={{
                maxHeight: 400,
                overflow: 'auto',
              }}
              fieldNames={{
                label: 'text',
                value: 'id',
                children: 'children',
              }}
              disabled={true}
              treeData={getLevelZeroJson()}
              treeCheckable={true}
              maxTagCount={5}
              showCheckedStrategy={TreeSelect.SHOW_PARENT}
              treeDefaultExpandAll={true}
            />
          );
        },
      },
      {
        field: `rangeAssetClassID`,
        label: `资产类型范围`,
        component: 'Render',
        colSpan: 2,
        disabled: true,
        render: (text) => {
          return (
            <TreeSelect
              multiple
              style={{
                width: '100%',
              }}
              dropdownStyle={{
                maxHeight: 400,
                overflow: 'auto',
              }}
              fieldNames={{
                label: 'name',
                value: 'id',
                children: 'children',
              }}
              treeData={addDisabledToTreeData(assetType)}
              treeCheckable={true}
              maxTagCount={3}
              treeDefaultExpandAll={true}
            />
          );
        },
      },
      {
        field: `rangeStartDate`,
        label: `取得开始时间`,
        component: 'Input',
        disabled: true,
        colSpan: 1,
      },
      {
        field: `rangeEndDate`,
        label: `取得结束时间`,
        component: 'Input',
        disabled: true,
        colSpan: 1,
      },
      {
        field: `inventoryInfo`,
        label: `盘点说明`,
        component: 'InputTextArea',
        disabled: true,
        placeholder: '自动带出',
        // required: !disabled,
        colSpan: 2,
        allowClear: true,
        showCount: true,
        maxLength: 200,
        autoSize: { minRows: 2, maxRows: 4 },
      },
      {
        field: `reportURL`,
        label: `相关附件`,
        component: 'Render',
        disabled: true,
        colSpan: 1,
        placeholder: '自动带出',
        render: (text, record) => {
          return (
            <div
              style={{
                height: '100%',
                display: 'flex',
                alignItems: 'center',
                marginLeft: '8px',
              }}
            >
              {record?.['reportURL']
                ? splitFileUrl(record?.['reportURL'])?.map((e, i) => {
                    return (
                      <div>
                        <Tooltip title={e.attachName} key={new Date().getTime() * 25615265152 + e?.attachName}>
                          <a
                            onClick={() => {
                              message.success('下载中，请稍后...');
                              downloadTemplate('/assetInfo/downloadFile', e?.attachName, e?.attachUrl, () => {});
                            }}
                          >
                            <MyIcon type="icon-file-text-fill" />
                            &nbsp;
                            {getFileNameNotType(e.attachName, 8)}
                          </a>
                        </Tooltip>
                        {/* 轻阅读预览 */}
                        <Tooltip title={'在线预览'}>
                          <Button type="link" size="small" onClick={() => onOpenReadOfdWord(e?.attachUrl)} icon={<EyeOutlined />} />
                        </Tooltip>
                      </div>
                    );
                  })
                : '--'}
            </div>
          );
        },
      },
    ];
    return tempArr;
  }, [infoObj, assetType]);

  // 表格表单配置信息
  const [config, BasicMethods] = useDescriptions({
    labelWidth: 200,
    basicForm: changeFromRef,
    schemas: [
      {
        label: '申请日期',
        field: 'createTime',
        component: 'Input',
        placeholder: '自动带出',
        disabled: true,
      },
      {
        field: `applyCode`,
        label: `流水单号`,
        component: 'Input',
        disabled: true,
        placeholder: '自动带出',
      },
      {
        label: '申请人',
        field: 'createrName',
        component: 'Input',
        placeholder: '自动带出',
        disabled: true,
      },
      {
        label: '联系电话',
        field: 'createPhone',
        component: 'Input',
        placeholder: '自动带出',
        disabled: true,
      },
      {
        label: '申请部门/单位',
        field: 'createDepartmentName',
        component: 'Input',
        placeholder: '自动带出',
        disabled: true,
      },
      {
        label: '职务岗位',
        field: 'createPositionName',
        component: 'Input',
        placeholder: '自动带出',
        disabled: true,
      },
    ],
  });
  // 表格表单配置信息
  const [ReConfig, ReMethods] = useDescriptions({
    labelWidth: 200,
    basicForm: changeFromRef,
    schemas: schemasArr(),
  });

  return (
    <>
      <div className="commonTabsBodyDom">
        <div className={Cls('tabsBodyInfoDom', `${styleFixCls}updateFormBox`)}>
          <ScrollBarLayout style={{ padding: '20px 10%' }}>
            <Spin spinning={mapLoading || DetailPushLoading}>
              <TypographyTitle children={'盘点计划申请'} style={{ textAlign: 'center', borderLeft: 'none' }} level={1} />
              <TypographyTitle children={'基本信息'} style={{ margin: '25px 0px 20px' }} level={2} />
              <Descriptions config={config} />

              <TypographyTitle children={'盘点计划信息'} style={{ margin: '25px 0px 20px' }} level={2} />
              <Descriptions config={ReConfig} />
            </Spin>
          </ScrollBarLayout>
        </div>
      </div>
    </>
  );
};

export default connect(({ baseLogin, navTab }: Record<string, any>) => ({
  curRes: baseLogin?.permissions,
  navTab,
}))(DetailInfoCenterViewMainOA);
